/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package devbureau.servlet;

import devbureau.fstore.common.StoreFactory;
import devbureau.fstore.common.print.report.PrintBillReport;
import devbureau.fstore.common.report.Bill;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import static devbureau.fstore.util.Utilities.DateTime.getStartDate;
import static devbureau.fstore.util.Utilities.DateTime.parseShort;
import static devbureau.fstore.util.Utilities.DateTime.formatShort;
/**
 *
 * @author admin
 */
public class PrintBillReportServlet extends HttpServlet {
   private static final Logger log = Logger.getLogger(PrintBillReportServlet.class);
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

         String excel = request.getParameter(Constants.EXCEL);
         Date from = parseShort(request.getParameter(Constants.FROM));
         Date to = parseShort(request.getParameter(Constants.TO));

         log.debug("process Request -> excel["+excel+"] from["+from+"] to["+to+"]");
         if(Constants.EXCEL.equals(excel)){  //user wants to get excel. Dates are ready.
            from = getStartDate(from);
            to = getStartDate(to);
        }
        response.setContentType(".xls application/vnd.ms-excel");
        response.setHeader( "Content-Disposition", "attachment; filename=\"bill_report_"+formatShort(from)+"_"+formatShort(to)+".xls\"");
        OutputStream out = response.getOutputStream();
        try {
            List<Bill> bills = StoreFactory.getStore().getBillReport(from, to);
            String billSize = bills !=null ? String.valueOf(bills.size()) : "NULL";
            log.debug("Starting to write report to excel... Size is["+billSize+"]");
            if(bills!=null && bills.size()>0){
                new PrintBillReport(bills, out).writeReport();
            }
        } catch(Exception e){
            log.error("Error while getting xls for bill report. " + e.getMessage());
            request.setAttribute(Constants.MESSAGE_ERROR, e.getMessage());
        }
        finally {
            if(out!=null){
                out.flush();
                out.close();
            }
        }
    } 

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
}
